package com.leet.code.simple_array;

import java.util.*;

/**
 * @description:
 * @author: WYG
 * @time: 2020/12/3 14:04
 */

public class CommonChars {
    public List<String> commonChars(String[] A) {
        int[] acs = getCs(A[0]);
        for (int i = 1; i < A.length; i++) {
            int[] aics = getCs(A[i]);

            for (int j = 0; j < acs.length; j++) {
                if (acs[j] > aics[j]) {
                    acs[j] = aics[j];
                }
            }
        }

        List<String> list = new LinkedList<>();
        for (int i = 0; i < acs.length; i++) {
            String e = Character.toString('a' + i);

            while (acs[i]-- > 0) {
                list.add(e);
            }
        }
        return list;
    }
    private int[] getCs(String s) {
        int[] cs = new int[26];
        for (char c : s.toCharArray()) {
            cs[c - 'a']++;
        }
        return cs;
    }

    public List<String> other_commonChars(String[] A) {
        int[] minfreq = new int[26];
        Arrays.fill(minfreq, Integer.MAX_VALUE);
        for (String word: A) {
            int[] freq = new int[26];
            int length = word.length();
            for (int i = 0; i < length; ++i) {
                char ch = word.charAt(i);
                ++freq[ch - 'a'];
            }
            for (int i = 0; i < 26; ++i) {
                minfreq[i] = Math.min(minfreq[i], freq[i]);
            }
        }

        List<String> ans = new ArrayList<String>();
        for (int i = 0; i < 26; ++i) {
            for (int j = 0; j < minfreq[i]; ++j) {
                ans.add(String.valueOf((char) (i + 'a')));
            }
        }
        return ans;
    }
}
